package dbexel.system;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import dbexel.model.dao.WorkSheetDao;
import dbexel.model.dao.WorkSheetDaoImpl;
import dbexel.model.mapping.WorkSheet;

public class InitDerbyDatabaseServer implements ServletContextListener {

	public void contextInitialized(ServletContextEvent in_sce) {
		Connection embeddedConn = null;
		System.out.println("Derby : Starting Embedded Network Server");
		System.setProperty("derby.drda.startNetworkServer","true");

		// Booting derby
		try {
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();			
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Derby : Embedded Network Server Started");
		
		System.out.println("Derby : Creating Meta Data");
		WorkSheetDao l_wsDao = new WorkSheetDaoImpl();
		int x = l_wsDao.fetchAllWorkSheets().size();
		System.out.println("Derby : Meta Data Created");
	}

	public void contextDestroyed(ServletContextEvent in_sce) {
        boolean gotSQLExc = false;  
		try {
			DriverManager.getConnection("jdbc:derby:;shutdown=true");
		} catch (SQLException e) {
		    gotSQLExc = true;  
        }  

        if (!gotSQLExc) {  
            System.out.println("Database did not shut down normally");  
        } else {  
            System.out.println("Database shut down normally");  
        } 
        
        System.out.println("Derby : Stopped Embedded Network server");  
		
	}

}
